package com.zz.push.util;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.zz.push.message.server.CurrentDateMessage;
import io.netty.channel.Channel;
import org.springside.modules.mapper.JsonMapper;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class PushClientUtil {

    private static BiMap<Integer, String> macChannelHashCode = HashBiMap.create();
    private static Map<Integer, Channel> macChannel = new HashMap<>();

    public static void put(Channel channel, String mac) {
        macChannelHashCode.put(channel.hashCode(), mac);
        macChannel.put(channel.hashCode(), channel);
    }

    public static void remove(Channel channel) {
        macChannelHashCode.remove(channel.hashCode());
        macChannel.remove(channel.hashCode());
    }

    public static void pushCurrentDate(String mac) {
        Integer hashCode = macChannelHashCode.inverse().get(mac);
        Channel channel = macChannel.get(hashCode);
        CurrentDateMessage currentDateMessage = new CurrentDateMessage();
        currentDateMessage.setCode(10001);
        currentDateMessage.setCurrentDate(new Date());
        if (channel != null) {
            channel.writeAndFlush(JsonMapper.nonDefaultMapper().toJson(currentDateMessage) + "\r\n");
        } else {
            JedisPoolUtil.getJedis().rpush("PERSISTENCE:" + mac, JsonMapper.nonDefaultMapper().toJson(currentDateMessage));
        }
    }

    public static void pushPersistenceMessage(String mac) {
        Integer hashCode = macChannelHashCode.inverse().get(mac);
        Channel channel = macChannel.get(hashCode);
        List<String> messages = JedisPoolUtil.getJedis().lrange("PERSISTENCE:" + mac, 0,
                JedisPoolUtil.getJedis().llen("PERSISTENCE:" + mac) - 1);

        if (messages != null) {
            for (String message : messages) {
                channel.writeAndFlush(message + "\r\n");
            }
            JedisPoolUtil.getJedis().del("PERSISTENCE:" + mac);
        }
    }

    public static void pushMessage2All() {
        for (Channel channel : macChannel.values()) {
            channel.writeAndFlush("to all: 主动推送的消息\r\n");
        }
    }

    public static void kick(String mac) {
        Integer hashCode = macChannelHashCode.inverse().get(mac);
        Channel channel = macChannel.get(hashCode);
        if (channel != null) {
            remove(channel);
            channel.close();
        }
    }
}
